package kandl.automation.reporting.testrail;

import org.apache.log4j.Logger;

import java.util.Map;

import kandl.automation.Browser;
import kandl.automation.reporting.ResultReporter;
import kandl.automation.reporting.testrail.model.*;
import kandl.automation.testsuite.TestCase;
import kandl.automation.testsuite.TestSuite;
import static com.google.common.collect.Maps.newHashMap;

public class TestRailReporter implements ResultReporter {

    private static final Logger logger = Logger.getLogger(TestRailReporter.class);

    private final TestRailRepository testRailRepository;

    private final Map<String, TestRailPlan> planMap;

    public TestRailReporter(TestRailRepository testRailRepository) {
        this.testRailRepository = testRailRepository;
        this.planMap = newHashMap();
    }

    @Override
    public void pass(TestCase testCase, Browser browser, TestSuite testSuite) {
        sendResult(new TestRailTestResult(TestRailStatus.success), testCase, browser, testSuite);
    }

    @Override
    public void fail(TestCase testCase, Browser browser, TestSuite testSuite, String comment) {
        sendResult(new TestRailTestResult(TestRailStatus.fail, comment), testCase, browser, testSuite);
    }

    private void sendResult(TestRailTestResult result, TestCase testCase, Browser browser, TestSuite testSuite) {
        TestRailRun run = getRun(testSuite, browser);
        if (run == null) {
            return;
        }
        String runId = run.getId();
        String caseId = testCase.getCaseId();
        testRailRepository.postTestResult(runId, caseId, result);
    }

    private TestRailRun getRun(TestSuite testSuite, Browser browser) {
        for (TestRailEntry entry : getPlan(testSuite).getEntries()) {
            for (TestRailRun run : entry.getRuns()) {
                if (run.getSuiteId()!=null && run.getSuiteId().equals(testSuite.getId()) &&
                	run.getConfig().contains(browser.getName())) {
                    return run;
                }
            }
        }
        logger.warn("No testrail run found for browser: " + browser.getName());
        return null;
    }

    private TestRailPlan getPlan(TestSuite testSuite) {
        synchronized (planMap) {
            TestRailPlan plan = planMap.get(testSuite.getId());
            if (plan == null) {
                plan = testRailRepository.getPlan(testSuite.getPlanId());
                planMap.put(testSuite.getId(), plan);
            }
            return plan;
        }
    }
}
